package com.yonyou.crm.cum.contact.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.cum.contact.itf.IContactBizService;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.service.CustomerSalesBizServiceImpl;
import com.yonyou.crm.sys.dataright.entity.RightActionEnum;
import com.yonyou.crm.sys.dataright.entity.RightObjectEnum;
import com.yonyou.crm.sys.dataright.service.RightServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.yonyou.crm.bpub.list.entity.AppListSpecialVO;
import com.yonyou.crm.bpub.list.entity.AppListVO;
import com.yonyou.crm.bpub.list.entity.AppListValueVO;
import com.yonyou.crm.bpub.refervalue.entity.ReferDataVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.search.entity.AppSearchPlanEnum;
import com.yonyou.crm.cum.contact.entity.ContactVO;
import com.yonyou.crm.sact.schedule.entity.ScheduleObjectVO;
import com.yonyou.crm.sact.schedule.service.ScheduleObjectBizServiceImpl;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.crm.cum.contact.entity.ContactDO;
import com.yonyou.crm.cum.customer.service.CustomerBizServiceImpl;

public class ContactBizServiceImpl extends BaseBizServiceImpl<ContactDO> implements IContactBizService {
	
	@Autowired
	private SysOrgBizServiceImpl orgService;
	@Autowired
	private EnumBizServiceImpl enumService;
	@Autowired
	private UserBizServiceImpl userService;
	@Autowired
    ScheduleObjectBizServiceImpl scheduleObjectService;
	@Autowired
	private RightServiceImpl rightService;
	@Autowired
	private CustomerBizServiceImpl customerService;
	@Autowired
	private CustomerSalesBizServiceImpl saleService;
	
	public Page<ContactVO> getList(Page<ContactVO> page,Map<String, Object> paramMap) {
		Page<ContactDO> contactPage = null;
		if (paramMap != null) {
			//全部、我负责、我参与、我关注、当月生日、最近查看
			if ((paramMap.containsKey("option")) && (paramMap.get("option") != null)) {
				int option = (int)paramMap.get("option");
				String optionSql = "";
				if (option == AppSearchPlanEnum.OWNER.getValue()) {
    				optionSql = " and contact.id in (select con_id from cum_contact_owner where owner_user_id = "+InvocationInfoProxy.getParameter(LoginContextConstant.UserId)+")";
    			} else if (option == AppSearchPlanEnum.REL.getValue()) {
    				optionSql = " and contact.id in (select con_id from cum_contact_reluser where rel_user_id = "+InvocationInfoProxy.getParameter(LoginContextConstant.UserId)+")";
    			} else if (option == AppSearchPlanEnum.FOLLOW.getValue()) {
    				//TODO联系人关注表未创建
					//optionSql = " and contact.id in (select con_id from cum_contact_follow where user_id = "+InvocationInfoProxy.getParameter(LoginContextConstant.UserId)+")";
    				optionSql = "";
				} else if (option == AppSearchPlanEnum.BIRTHMONTH.getValue()) {
					//TODO当前月生日
					optionSql = "";
				} else if (option == AppSearchPlanEnum.VIEW.getValue()) {
					//TODO最近查看条件
					optionSql = "";
				} else {
					//TODO全部
					optionSql = "";
				}
				paramMap.put("option", optionSql);
			}
			contactPage = super.pageSelect(ContactDO.class, page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		}
		else {
			contactPage = super.pageSelect(ContactDO.class, page, null, null);
		}

		Page<ContactVO> contactVOPage = ModelUtil.copyPageModel(contactPage, ContactVO.class);
		transContact(contactVOPage.getData());
		return contactVOPage;
	}
	
	public ContactVO getDetail(Long id) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ownerId", new Long(InvocationInfoProxy.getParameter("id")));
		paramMap.put("id", id);
		ContactDO contactDO = (ContactDO)dao.selectOne(ContactDO.class, "getContactById", paramMap);
		ContactVO contactVO = ModelUtil.copyModel(contactDO, ContactVO.class);
		if (contactVO != null) {
			transContact(Arrays.asList(contactVO));
		}
		return contactVO;
	}

	public ContactVO save(ContactVO contact) {
		ContactDO contactDO = ModelUtil.copyModel(contact, ContactDO.class);
		ContactDO result=super.saveVO(contactDO);
		return ModelUtil.copyModel(result, ContactVO.class);
	}
	
	public ContactVO save(ContactVO contact, Map<String, Object> param) {
		contact = save(contact);
		Map<String, String> relateMap = (Map<String, String>)param.get("relateMap");
		if ((relateMap != null) && (relateMap.size() > 0)) {
        	//TODO写入日程关联表
        	ScheduleObjectVO scheduleObject = new ScheduleObjectVO();
        	scheduleObject.setScheduleId(Long.valueOf(relateMap.get("id")));
        	Integer scheduleType = ScheduleObjectBizServiceImpl.getScheduleType(relateMap.get("type"));
        	scheduleObject.setScheduleType(scheduleType);
        	Long objType = ScheduleObjectBizServiceImpl.getObjType("contact");
        	scheduleObject.setObjType(objType);
        	scheduleObject.setObjId(contact.getId());
        	// 设置业务子类型
        	long subBnsType = ScheduleObjectBizServiceImpl.getBizObjType(String.valueOf(param.get("subBnsType")));
        	scheduleObject.setObjBiztype(subBnsType);
        	scheduleObjectService.save(scheduleObject);
        }
		return contact;
	}
	
	@Override
	protected void beforeSaveVO(ContactDO cDO) {
		super.beforeSaveVO(cDO);
		Long orgId =  new Long(InvocationInfoProxy.getParameter("orgid"));
		Long loginUserID = new Long(InvocationInfoProxy.getParameter("id"));
		cDO.setGroupId(orgId);
		cDO.setOrgId(orgId);
		cDO.setCountry(1);
		cDO.setOwnerUserId(loginUserID);//TODO设置负责人
	}
	
	public ContactVO update(ContactVO contact) {
		ContactDO contactDO = ModelUtil.copyModel(contact, ContactDO.class);
		ContactDO result = super.updateVO(contactDO);
		return ModelUtil.copyModel(result, ContactVO.class);
	}
	
	@Override
	protected void beforeUpdateVO(ContactDO cDO) {
		super.beforeUpdateVO(cDO);
	}
	
	public int delete(Long id) {
		ContactDO contact = new ContactDO();
		contact.setId(id);
		return super.deleteVO(contact);
	}

	public void batchDelete(String[] ids) {
		super.batchDeleteByIDs(ContactDO.class, ids);
	}
	
	@Override
	protected void beforeDeleteVO(ContactDO cDO) {
		super.beforeDeleteVO(cDO);
	}
	
	public Object selectFieldsByIds(Object[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return dao.selectList(ContactDO.class, "selectFieldsByIds", para);
	}
	
	//根据Id数组获取联系人实例
	public List<ContactVO> selectVOByIds(String[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		List<ContactDO>  result= dao.selectVoList(ContactDO.class, "selectVOByIds", para);
		return ModelUtil.copyModelList(result,ContactVO.class);
	}
	
	private List<ContactVO> transContact(List<ContactVO> contactList) {
		if (contactList != null && contactList.size() > 0) {
			List<FieldRelation<ContactVO>> relations = new ArrayList<FieldRelation<ContactVO>>();
			relations.add(new RefFieldRelation<ContactVO>(ContactVO.class, "groupId", new String[]{"groupName"}, orgService, "selectFieldsByIds"));
			relations.add(new RefFieldRelation<ContactVO>(ContactVO.class, "orgId", new String[]{"orgName"}, orgService, "selectFieldsByIds"));
			relations.add(new RefFieldRelation<ContactVO>(ContactVO.class, "deptId", new String[]{"deptName"}, orgService, "selectFieldsByIds"));
			relations.add(new EnumFieldRelation<ContactVO>(ContactVO.class, "enableState", "enableStateName", enumService, "enable_state"));
			relations.add(new EnumFieldRelation<ContactVO>(ContactVO.class, "mainContact", "mainContactName", enumService, "contact_main"));
			relations.add(new EnumFieldRelation<ContactVO>(ContactVO.class, "marriage", "marriageName", enumService, "contact_marriage"));
//			relations.add(new RefFieldRelation<ContactVO>(ContactVO.class, "customer", new String[]{"customerInfo"}, customerService, "selectFieldsByIds"));
//			relations.add(new EnumFieldRelation<ContactVO>(ContactVO.class, "attitude", "attitudeName", enumService, "contact_attitude"));
			new FieldRelationHandler<ContactVO>().handler(contactList, relations);
			//因为user mapper的idGetUser返回类型由UserVO改为UserDO所引起的修改
			//（取消在mapper里使用association,改为调用user的getDetail方法）
			for(ContactVO contact : contactList) {
				Long userId = contact.getOwnerUserId();
				UserVO userVO = userService.getDetail(userId);
				contact.setOwnerUserInfo(userVO);
				Long customerId=contact.getCustomer();
				if(customerId!=null){
					contact.setCustomerInfo(customerService.getDetail(customerId));
				}
			}
		}
		
		return contactList;
	}
	
	//获取联系人参照
	public List<ReferDataVO> getRefervalues(Page<ContactVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<ContactDO> pageDO = dao.pageSelect(ContactDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		Page<ContactVO> pageVO = ModelUtil.copyPageModel(pageDO, ContactVO.class);
		List<ContactVO> voList = pageVO.getData();
		
		List<ReferDataVO> rsList = new ArrayList<ReferDataVO>();
		for (ContactVO vo : voList) {
			ReferDataVO referDataVO = new ReferDataVO();
			referDataVO.setId(vo.getId().toString());
			referDataVO.setValue(vo.getName());
			
			rsList.add(referDataVO);
		}
		return rsList;
	}
	
	//获取联系人参照
	public List<ContactVO> getRefervaluesForApp(Page<ContactVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<ContactDO> pageDO = dao.pageSelect(ContactDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		Page<ContactVO> pageVO = ModelUtil.copyPageModel(pageDO, ContactVO.class);
		List<ContactVO> voList = pageVO.getData();
		return voList;
	}
	
	public List<AppListVO> getListForApp(Map<String, Object> map) {
    	List<ContactDO> pageDO = dao.selectVoList(ContactDO.class, "NoPageContact", map);
		List<ContactVO> dataList = ModelUtil.copyModelList(pageDO, ContactVO.class);
    	List<AppListVO> list = new ArrayList<AppListVO>();
		for (int i = 0; i<dataList.size(); i++) {
			ContactVO contact = dataList.get(i);

			AppListVO listVO = new AppListVO();
			listVO.setId(contact.getId());
			
			List<List<AppListValueVO>> valueList = new ArrayList<>();
			List<AppListValueVO> colList = new ArrayList<>();

			AppListValueVO listValue = new AppListValueVO();
			listValue.setItemkey("photo");
			listValue.setDisplayvalue(contact.getPhoto());
			colList.add(listValue);
			
			listValue = new AppListValueVO();
			listValue.setItemkey("name");
			listValue.setDisplayvalue(contact.getName());
			colList.add(listValue);
			
			listValue = new AppListValueVO();
			listValue.setItemkey("post");
			listValue.setDisplayvalue(contact.getPost());
			colList.add(listValue);
			
			listValue = new AppListValueVO();
			listValue.setItemkey("deptName");
			listValue.setDisplayvalue(contact.getDeptName());
			colList.add(listValue);
			
			valueList.add(colList);

			listVO.setValuelist(valueList);
			list.add(listVO);
		}
		return list;
    }
	
	/**
	 * 关注
	 * @param id
	 * @return
	 */
	public int saveFollow(Long id) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("TenantId", InvocationInfoProxy.getTenantid());
		param.put("contactId", id);
		param.put("userId", InvocationInfoProxy.getParameter("id"));
		int count = dao.countAll(ContactDO.class, "countFollow", param);
		if (count > 0) {
			return 1;
		}
		return dao.saveSql(ContactDO.class, "insertFollow", param);
	}
	
	/**
	 * 删除关注
	 * @param id
	 * @return
	 */
	public int deleteFollow(Long id) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", InvocationInfoProxy.getTenantid());
		param.put("contactId", id);
		param.put("userId", InvocationInfoProxy.getParameter("id"));
		return dao.deleteSql(ContactDO.class, "deleteFollow", param);
	}
	/**
	 * 获取联系人相关列表
	 * @param cusId
	 * @param limit
	 * @return
	 */
	public Map<String,Object> getRelatedListForApp(Long cusId, Integer limit){
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("cusId", cusId);
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		List<ContactVO> listForNum = this.selectContactByCumId(paraMap);
		paraMap.put("limit", limit);
		List<ContactVO> list = this.selectContactByCumId(paraMap);
		Map<String,Object> datalistMap = new HashMap<String,Object>();
		datalistMap.put("type", "contact");
		datalistMap.put("name", "联系人");
		datalistMap.put("num", listForNum == null ? 0 : listForNum.size());

		Long userId = new Long(InvocationInfoProxy.getParameter("id"));
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("cumId", cusId);
		paramMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		paramMap.put("orgId", new Long(InvocationInfoProxy.getParameter("orgid")));
		List<CustomerSalesVO> saleList = saleService.selectByCustomer(paramMap);

		if (saleList != null) {
			boolean isOnwer = false;
			boolean isManager = false;
			for (int i = 0; i < saleList.size(); i++) {
				CustomerSalesVO saleInfo = saleList.get(i);
				if (userId.toString().equals(saleInfo.getOwnerUserId().toString())) {
					isOnwer = true;
				}
				Long deptId = saleInfo.getOwnerDeptId();
				List<String> managerIdList = userService.getSMIdListByDeptId(deptId);
				if (managerIdList != null && managerIdList.contains(userId.toString())) {
					isManager = true;
				}
			}
			if (isManager || isOnwer) { //只有负责员工 或者 销售经理 才可以添加
				datalistMap.put("isnew", "Y");
			}

		}

		if(list != null && list.size() >0 ){

			List<AppListVO> listapp = new ArrayList<AppListVO>();
			for(ContactVO vo : list){
				AppListVO listVO = new AppListVO();
				listVO.setId(vo.getId());

				List<List<AppListValueVO>> valueList = new ArrayList<List<AppListValueVO>>();
				List<AppListValueVO> colList = new ArrayList<AppListValueVO>();
				AppListValueVO listValue = new AppListValueVO();
				listValue.setItemkey("contactName");
				listValue.setDisplayvalue(vo.getName());
				colList.add(listValue);

				listValue = new AppListValueVO();
				listValue.setItemkey("nomalkey");
				listValue.setDisplayvalue(vo.getPost());
				colList.add(listValue);

				valueList.add(colList);
				listVO.setValuelist(valueList);

				List<AppListSpecialVO> speciallist=new ArrayList<AppListSpecialVO>();
				AppListSpecialVO appListSpecialVO=new AppListSpecialVO();
				appListSpecialVO.setType("phonetype");
				appListSpecialVO.setPosition("position");
				List<String> valList=new ArrayList<String>();
				valList.add(vo.getMobile());
				valList.add(vo.getHomePhone());
				valList.add(vo.getOfficePhone());
				appListSpecialVO.setValue(valList);
				speciallist.add(appListSpecialVO);
				listVO.setSpeciallist(speciallist);

				Map<String, String> hidelist=new HashMap<String, String>();
				hidelist.put("key","");
				hidelist.put("value","");
				listVO.setHidelist(hidelist);
				listapp.add(listVO);
			}
			datalistMap.put("detaillist", listapp);
		}
		return datalistMap;

	}
	private List<ContactVO> selectContactByCumId(Map<String, Object> paraMap){
		List<ContactDO> listDO = dao.selectVoList(ContactDO.class, "selectByCumId", paraMap);
		List<ContactVO> listVO= ModelUtil.copyModelList(listDO,ContactVO.class);
		transContact(listVO);
		return listVO;
	}

	public Page<ContactVO> getMyOwnerList(Page<ContactVO> page,
										  Map<String, Object> paramMap) {

		String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
		String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");// 所属公司
		String deptIdStr = (String) InvocationInfoProxy.getParameter("deptid");// 部门id
		String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
		Long userId = Long.parseLong(userIdStr);
		Long orgId = Long.parseLong(orgIdStr);
		Long deptId = Long.parseLong(deptIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		paramMap.put("id", userId);
		paramMap.put("org_id", orgId);
		paramMap.put("dept_id", deptId);
		paramMap.put("tenant_id", tenantId);

		//数据权限
		String roleIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.RoleId);
		Long objId = RightObjectEnum.CUSTOMEROBJECT.getValue();
		Long actionId = (long) RightActionEnum.VIEW.getValue();
		String dataRightSql = rightService.getRightSql(Long.parseLong(roleIdStr), objId, actionId);
		paramMap.put("rightSql", dataRightSql);
		Page<ContactDO> pageList = null;
		pageList = dao.pageSelect(ContactDO.class, page, "selectByRight", "countByRight", paramMap);
		Page<ContactVO> result = ModelUtil.copyPageModel(pageList, ContactVO.class);
		transContact(result.getData());
		return result;
	}

	public void changeOwner(ContactDO contactDO) {
		dao.updateSql(ContactVO.class, "changeOwner", contactDO);
    }	
	
	public int getCountByDeptOrOrg(Map<String, Object> paramMap){
		return dao.countAll(ContactDO.class, "getCountByDeptOrOrg", paramMap);
	}
	
	public List<String> getContactNameById(String[] ids){
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		List<ContactDO>  result= dao.selectVoList(ContactDO.class, "selectVOByIds", para);
		if(result==null||result.size()==0)
			return null;
		List<String> list=new ArrayList<String>();
		for(ContactDO cDO:result){
			list.add(cDO.getName());
		}
		return list;
	}
}
